package base;

import java.util.ArrayList;

import values.Value;
import values.Boolean;
import values.Integer;
import values.Array;
import values.FantaString;

public class Parser {

	/*
	 * Returns a value corresponding to the string.
	 * 
	 * It can be a boolean, an integer, an array, or if none of them, then a
	 * FantaString with s's content is returned.
	 */

	public static Value parse(String s) {

		if (s.equals("true"))
			return new Boolean(true);
		else if (s.equals("false"))
			return new Boolean(false);

		try {
			return new Integer(s);
		} catch (NumberFormatException e) {
			;
		}

		s = s.trim();

		if (s.startsWith("[") && s.endsWith("]")) {

			s = s.substring(1, s.length() - 1);

			String[] split = divide(s);
			Value[] values = new Value[split.length];

			for (int i = 0; i < split.length; i++) {
				Value value = parse(split[i]);
				if (value != null)
					values[i] = value;
				else
					return null;
			}

			return new Array(values);
		}

		return new FantaString(s);
	}

	/*
	 * Returns an array similar to s.split(" "). The difference is that, it does
	 * not split when the " " is inside '[' and ']'
	 * 
	 * In this way, the subarrays are not split up.
	 */

	private static String[] divide(String s) {

		ArrayList<String> divison = new ArrayList<String>();
		boolean test = true;

		while (test) {

			if (s.indexOf('[') == 0) {

				int i;
				int crochetCount = 1;

				for (i = 1; i < s.length() && crochetCount != 0; i++) {
					if (s.charAt(i) == '[')
						crochetCount++;
					else if (s.charAt(i) == ']')
						crochetCount--;
				}

				if (crochetCount == 0) {
					divison.add(s.substring(0, i));
				} else {
					return null;
				}

				if (i + 1 <= s.length())
					s = s.substring(i + 1);
				else
					test = false;

			} else {
				int firstSpace = s.indexOf(' ');

				if (firstSpace > 0) {
					divison.add(s.substring(0, firstSpace));
					s = s.substring(firstSpace + 1);
				} else {
					divison.add(s);
					test = false;
				}
			}

		}

		String[] array = new String[divison.size()];
		return divison.toArray(array);

	}
}
